package com.ruoyi.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MediaSyncUtil {
    private static final Logger log = LoggerFactory.getLogger(MediaSyncUtil.class);

    // 设置 ffmpeg 的完整路径
    private static final String FFMPEG_PATH = "D:/ffmpeg/ffmpeg7.0/bin/ffmpeg.exe";
    private static final String RECORDING_DIR = "E:\\Sync\\"; // 本地存储目录

    /**
     * 同步音视频文件
     * @param videoFileName 视频文件名
     * @param audioFileName 音频文件名
     * @param outputPath 输出文件完整路径
     * @return 同步后的文件路径
     */
    public String syncMediaFiles(String videoFileName, String audioFileName, String outputPath) {
        Process process = null;
        try {
            // 修改文件路径构建方式，检查文件名是否已包含完整路径
            String videoPath = videoFileName.contains(RECORDING_DIR) ? 
                videoFileName : RECORDING_DIR + "video\\" + videoFileName;
            String audioPath = audioFileName.contains(RECORDING_DIR) ? 
                audioFileName : RECORDING_DIR + "audio\\" + audioFileName;

            log.info("开始同步音视频文件 - 视频：{}，音频：{}", videoPath, audioPath);

            // 构建命令列表
            List<String> command = new ArrayList<>();
            command.add(FFMPEG_PATH);
            command.add("-i");
            command.add(videoPath);
            command.add("-i");
            command.add(audioPath);
            command.add("-c:v");
            command.add("libx264");  // 设置视频编码为libx264
            command.add("-c:a");
            command.add("libmp3lame");  // 设置音频编码为libmp3lame
            command.add("-strict");
            command.add("experimental");
            command.add("-map");
            command.add("0:v:0");
            command.add("-map");
            command.add("1:a:0");
            command.add("-y");
            command.add(outputPath);

            log.info("FFmpeg命令: {}", String.join(" ", command));
            // 创建进程构建器
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.directory(new java.io.File(RECORDING_DIR));
            processBuilder.redirectErrorStream(true);

            // 启动进程
            process = processBuilder.start();

            // 读取输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info("FFmpeg输出：{}", line);
                }
            }

            // 等待进程完成，设置超时时间
            if (!process.waitFor(30, TimeUnit.MINUTES)) {
                process.destroyForcibly();
                throw new RuntimeException("音视频同步超时");
            }

            int exitCode = process.exitValue();
            if (exitCode != 0) {
                throw new RuntimeException("音视频同步失败，FFmpeg退出码：" + exitCode);
            }

            log.info("音视频同步完成：{}", outputPath);
            return outputPath;

        } catch (Exception e) {
            log.error("音视频同步失败", e);
            throw new RuntimeException("音视频同步失败: " + e.getMessage());
        } finally {
            // 确保进程被正确关闭
            if (process != null && process.isAlive()) {
                process.destroyForcibly();
            }
        }
    }
}